package com.spring.datasource.aop;

import com.spring.datasource.util.DynamicDataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 数据源AOP切面定义
 */
@Component
@Aspect
@Slf4j
public class RequestMappingAspect {
    //切换放在mapper接口的方法上，所以这里要配置AOP切面的切入点
//    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
//    @Pointcut("execution(@org.springframework.web.bind.annotation.RequestMapping public * *.*(..))")
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)") // 所有被@AdviceAnnotation标注的类都将匹配
    public void requesrtMapping() {
    }

    @Around("requesrtMapping()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前注解方法
        MethodSignature methodSignature = (MethodSignature) joinPoint
                .getSignature();
        Method method = methodSignature.getMethod();

        try {

            if (StringUtils.isEmpty(MDC.get("mdc_trace_id"))) {
                String verifyCode = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));
                DynamicDataSourceHolder.putThreadLocal(verifyCode);
                MDC.put("mdc_trace_id", verifyCode);
            } else {
                DynamicDataSourceHolder.putThreadLocal(MDC.get("mdc_trace_id"));
            }

            log.info(method.getName());
        } catch (Exception ex) {
            throw ex;
        }


        Object object = joinPoint.proceed();
        DynamicDataSourceHolder.removeThreadLocal();

        return object;
    }

}
